﻿using BestPrice.App.ServiceCommunicator;
using BestPrice.Common;
using BestPrice.GridApp.Data;
using BestPrice.Library;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Grouped Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234231

namespace BestPrice.GridApp
{
    /// <summary>
    /// A page that displays a grouped collection of items.
    /// </summary>
    public sealed partial class GroupedItemsPage : BestPrice.GridApp.Common.LayoutAwarePage
    {
        private List<Category> _Categories;
        public List<Category> Categories
        {
            get { return _Categories; }
            set { _Categories = value; }
        }

        private SampleDataSource SampleDataSource;

        public GroupedItemsPage()
        {
            this.InitializeComponent();

            progessBar.IsEnabled = false;
            progessBar.Visibility = Visibility.Collapsed;

            InititalData();
        }

        private async void InititalData()
        {
            var task = await BestPriceServiceCommunicator.GetCategoryList();
            _Categories = task.ToList<Category>();

            cbBox.ItemsSource = _Categories;
            cbBox.SelectedIndex = 0;
        }

        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            if (pageState != null)
            {
                _Categories = pageState["Categories"] as List<Category>;
                cbBox.ItemsSource = _Categories;

                cbBox.SelectedIndex = (int)pageState["SelectedIndexCategory"];

                SampleDataSource = pageState["SampleDataSource"] as SampleDataSource;
                groupedItemsViewSource.Source = SampleDataSource.AllGroups;

                txtSearchInfo.Text = pageState["Keyword"] as String;
            }
        }

        protected override void SaveState(Dictionary<string, object> pageState)
        {
            base.SaveState(pageState);

            pageState.Add("Categories", _Categories);
            pageState.Add("SelectedIndexCategory", cbBox.SelectedIndex);
            pageState.Add("SampleDataSource", SampleDataSource);
            pageState.Add("Keyword", txtSearchInfo.Text);
        }

        private void GroupTitleOnClick(object sender, RoutedEventArgs e)
        {
        }

        /// <summary>
        /// Invoked when an item within a group is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        private void ItemViewOnClick(object sender, ItemClickEventArgs e)
        {
            var item = ((Product)e.ClickedItem);
            this.Frame.Navigate(typeof(BrowserDetailPage), new List<String>() { item.Title, item.BaseUrl });
        }

        private async void SearchOnClick(object sender, RoutedEventArgs e)
        {
            String keyword = txtSearchInfo.Text.Trim();
            if (!String.IsNullOrEmpty(keyword))
            {
                var item = cbBox.SelectedItem as Category;
                if (item != null)
                {
                    progessBar.IsEnabled = true;
                    progessBar.Visibility = Visibility.Visible;
                    txtSearchInfo.IsReadOnly = true;

                    var groups = new List<SampleDataGroup>();
                    foreach (var web in item.WebSites)
                    {
                        var g = await LoadProducts(1, web, keyword);
                        groups.Add(g);
                    }

                    SampleDataSource = new SampleDataSource(groups);
                    groupedItemsViewSource.Source = SampleDataSource.AllGroups;

                    progessBar.IsEnabled = false;
                    progessBar.Visibility = Visibility.Collapsed;

                    txtSearchInfo.IsReadOnly = false;
                }
            }
        }

        private async Task<SampleDataGroup> LoadProducts(int groupdID, WebSite web, String keyword)
        {
            WebHandler handler = new WebHandler(web.BaseUrl, web.Method);
            var content = await handler.LoadContentAsync(web.SearchUrl, web.Parameter, keyword, web.ExtraParamater);

            var products = HtmlUtil.ParseProduct(content, web);

            var group = new SampleDataGroup(groupdID, web.Name);
            int pid = 1;
            foreach (var p in products)
            {
                group.Items.Add(new SampleDataItem(pid++, p.Title, p.Detail, p.Price, p.ImageUrl, p.BaseUrl, group));

                //if (pid == 4)
                //    break;
            }

            return group;
        }

        private void SearchInfoKeyUp(object sender, KeyRoutedEventArgs e)
        {
            if (!txtSearchInfo.IsReadOnly && e.Key == Windows.System.VirtualKey.Enter)
            {
                SearchOnClick(null, null);
            }
        }

        private bool IsClear = true;
        private void SearchInfoGotFocus(object sender, RoutedEventArgs e)
        {
            if (IsClear)
            {
                txtSearchInfo.Text = String.Empty;
                IsClear = false;
            }
        }

    }
}
